package com.lx.spring.mvc;

import com.lx.spring.mvc.web.MyDispatchServlet;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {
        // 加载 Spring 配置
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MvcConfig.class);
//        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MvcConfig.class);
        // 注册转发器Servlet 初始化IOC容器 接管所以请求
//        MyDispatchServlet servlet = new MyDispatchServlet(context);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", dispatcherServlet);
        // 设置服务器在启动时加载 DispatcherServlet
        registration.setLoadOnStartup(1);
        // 转发全部请求，必须配置响应地址为：/
        registration.addMapping("/");
        // 添加文件上传配置
        MultipartConfigElement mc = new MultipartConfigElement(
                "/",
                200 * 1024,
                1024 * 1024 * 1024,
                1024 * 1024 * 2);
        registration.setMultipartConfig(mc);

    }
}